package net.wanho.config;

import net.wanho.shiro.ShiroRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-07-25 16:43
 * Description：<描述>
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactoryBean.setSecurityManager(securityManager);

        // 设置过滤的url
        Map<String,String> map = new LinkedHashMap<>(); // 有序的map
        map.put("/login.jsp","anon"); // 不需要认证的页面
        map.put("/register.jsp","anon");
        map.put("/user/login","anon");
        map.put("/user/register","anon");

        map.put("/**","authc");

        // 设置认证的页面
        filterFactoryBean.setLoginUrl("/login.jsp"); // 没有认证的时候跳转到登录页面

        filterFactoryBean.setFilterChainDefinitionMap(map);

        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public Realm getShiroRealm(){
        ShiroRealm shiroRealm = new ShiroRealm();

        // 设置凭证匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5"); // 设置加密算法
        matcher.setHashIterations(1024); // 设置加密次数

        shiroRealm.setCredentialsMatcher(matcher);
        return shiroRealm;
    }

}
